from rest_auth.app_settings import create_token
from rest_auth.models import TokenModel
from rest_auth.serializers import TokenSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError, NotFound
from rest_framework.request import Request
from rest_framework.response import Response

from api.serializers.login_serializer import SmsCodeLoginSerializer
from api.utils.sms.send_sms import validate_sms_code
from app.models import FMUser


@api_view(['POST'])
def login_with_sms_code(request: Request):
    serializer = SmsCodeLoginSerializer(data=request.data)
    if serializer.is_valid():
        username = serializer.validated_data['phone_number']
        sms_code = serializer.validated_data['sms_code']
        if not validate_sms_code(username, sms_code):
            raise ValidationError(u"验证码不正确或已失效")
        try:
            user = FMUser.objects.get(username=username)
        except FMUser.DoesNotExist:
            raise NotFound(detail=u'用户不存在')
        create_token(TokenModel, user, serializer)
        return Response(TokenSerializer(user.auth_token).data,
                        status=status.HTTP_201_CREATED)
    else:
        raise ValidationError(serializer.errors)
